package com.base.app_core.service.pressenter;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.base.app_core.base.ActionPacketView;
import com.base.app_core.base.BaseView;
import com.base.app_core.base.impl.BasePresenter;
import com.base.app_core.model.MoneyData;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.Region;
import com.base.app_core.model.ServerIP;
import com.base.app_core.model.ShareUser;
import com.base.app_core.model.TodayHistoryStock;
import com.base.app_core.model.UserDeposit;
import com.base.app_core.model.UserHistoryStock;
import com.base.app_core.model.UserSmsVo;
import com.base.app_core.model.params.GetSmsCodeParam;
import com.base.app_core.model.rqview.WxLoginView;
import com.base.app_core.service.Retrofit.RestServer;
import com.base.app_core.service.rx.Callback;
import com.base.app_core.service.user.model.BindAliUserAcount;
import com.base.app_core.service.user.model.HomeRxBean;
import com.base.app_core.service.user.model.User;
import com.base.app_core.service.user.model.UserAccount;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.BeanPropertiesUtil;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.liteorm.DBHandleEvent;
import com.base.app_core.util.liteorm.MyIChatDBHelpUtils;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.StringUtils;
import com.hwangjr.rxbus.RxBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.inject.Inject;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;


/**
 * Created by jiansheng.li on 2018/1/16.
 */

public class XYBUPressenter extends BasePresenter<BaseView> {
    public static int WITHTYPE_ALI = 1;
    public static int WITHTYPE_WEIXIN = 0;

    @Inject
    public XYBUPressenter(RestServer server) {
        super(server);
    }

    @Inject
    User user;

    @Inject
    MoneyData moneyData;

    @Inject
    UserAccount userAccount;

    @Inject
    MyIChatDBHelpUtils myIChatDBHelpUtils;

    /**
     * @param parentId
     */
    public void fetchRegionByParentId(Long parentId) {
        invoke(mRestfull.fetchByParentId(parentId), new Callback<List<Region>>() {
        });
    }

    /**
     * 微信登录
     *
     * @param code
     */
    public void wxLogin(String code) {
        invoke(mRestfull.wxLogin(new WxLoginView(code)), new Callback<User>() {
            @Override
            public void onResponse(User data, Paginated paginated,Object extraData) {
                //登录成功
                try {
                    if (data.getIps() != null || data.getIps().size() != 0) {
                        String url = (String) data.getIps().get(new Random().nextInt(data.getIps().size())).getUrl();
                        RetrofitUrlManager.getInstance().setGlobalDomain(url);
                        //存储到数据库中
                        myIChatDBHelpUtils.addEvent(new DBHandleEvent(ServerIP.class, null, DBHandleEvent.CLEAR_TABLE), new DBHandleEvent(ServerIP.class, data.getIps(), DBHandleEvent.OBJECT_INSERT, 0));
                    }
                    AppConstants.Const.NeedLogin = false;
                    BeanPropertiesUtil.copyProperties(data, user);
                    F.j(user.getCreatedAt());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onResponse(data, paginated,extraData);
            }
        });
    }

    /**
     * 获取用户的详情
     */
    public void fetchUserAccount() {
        invoke(mRestfull.fetchUserAccount(), new Callback<UserAccount>() {
            @Override
            public void onResponse(UserAccount data, Paginated paginated,Object extraData) {
                try {
                    BeanPropertiesUtil.copyProperties(data, userAccount);
                    RxBus.get().post(new HomeRxBean(HomeRxBean.USER_ACCOUNT, userAccount));
                    F.j(user.getCreatedAt());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onResponse(data, paginated,extraData);
            }
        });
    }

    /**
     * 更新用户的经纬度信息
     *
     * @param longitude
     * @param latitude
     * @param pushTag
     * @param mobileType
     * @param provinceCode
     * @param cityCode
     * @param areaCode
     */
    public void postUserLoc(double longitude, double latitude, String pushTag, int mobileType, String provinceCode, String cityCode, String areaCode) {
        if (AppConstants.Const.NeedLogin)
            return;

        HashMap<String, Object> map = new HashMap<>();
        map.put("lat", latitude);
        map.put("lng", longitude);
        map.put("pushTag", pushTag);
        map.put("phoneType", mobileType);
        map.put("provinceCode", provinceCode);
        map.put("cityCode", cityCode);
        map.put("areaCode", areaCode);

        invoke(mRestfull.postUserLoc(map), new Callback<User>() {
            @Override
            public void onResponse(User data, Paginated paginated,Object extraData) {
                try {
                    Long id = data.getId();
                    if (id != null) {
                        Preferences.putLong(AppConstants.SP.ID, id);
                    }

                    String aliSnCode = data.getAliSnCode();
                    if (StringUtils.isEmpty(aliSnCode)) {
                        Preferences.putString(AppConstants.SP.SNCODE, aliSnCode);
                    }


                    BeanPropertiesUtil.copyProperties(data, user);
                    RxBus.get().post(user);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onResponse(data, paginated,extraData);
            }
        });
    }


    //获取用户收到红包总金额和发出红包总金额
    public void fetchRecvSndRedPacketCount() {
        invoke(mRestfull.fetchRecvSndRedPacketCount(), new Callback<Map>() {
            @Override
            public void onResponse(Map data, Paginated paginated,Object extraData) {
                super.onResponse(data, paginated,extraData);
                if (null != data) {
                    moneyData.setRecvMoney((String) data.get("recvCount"));
                    moneyData.setSndMoney((String) data.get("sndCount"));
                }
            }
        });
    }

    //获取历史股价列表
    public void fetchStockPriceLog(int pageNO) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.PAGE, pageNO);
        map.put(AppConstants.FIELD.PAGESIZE, AppConstants.Const.PAGESIZE);
        invoke(mRestfull.fetchStockPriceLog(map), new Callback<List<TodayHistoryStock>>() {
            @Override
            public void onResponse(List<TodayHistoryStock> data, Paginated paginated,Object extraData) {
                if (isnotNull()) {
                    mLifecycle.get().notifyData(data, TodayHistoryStock.class, paginated);
                }
            }
        });
    }

    //获取历史红包股数列表
    public void fetchStockCountLog(int pageNo) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.PAGE, pageNo);
        map.put(AppConstants.FIELD.PAGESIZE, AppConstants.Const.PAGESIZE);
        invoke(mRestfull.fetchStockCountLog(map), new Callback<List<UserHistoryStock>>() {
            @Override
            public void onResponse(List<UserHistoryStock> data, Paginated paginated,Object extraData) {
                if (isnotNull()) {
                    mLifecycle.get().notifyData(data, UserHistoryStock.class, paginated);
                }
            }
        });
    }

    //用户提现
    public void postDeposit(int type, String stockCount, String snCode) {
        if (type == WITHTYPE_WEIXIN) {//微信提现
            Map<String, Object> map = new HashMap<>();
            map.put(AppConstants.FIELD.STOCKCOUNT, stockCount);
            invoke(mRestfull.postDeposit(map), new Callback<Object>() {
                @Override
                public void onResponse(Object data, Paginated paginated,Object extraData) {
                    //提现成功
                    if (isnotNull()) {
                        if (mLifecycle.get() instanceof ActionPacketView.DepositView) {
                            ((ActionPacketView.DepositView) mLifecycle.get()).doDepositSuccess((String) data);
                        }
                    }
                }
            });
        } else if (type == WITHTYPE_ALI) {//支付宝提现
            Map<String, Object> map = new HashMap<>();
            map.put(AppConstants.FIELD.STOCKCOUNT, stockCount);
            map.put(AppConstants.FIELD.SNCODE, snCode);
            invoke(mRestfull.alipostDeposit(map), new Callback<Object>() {
                @Override
                public void onResponse(Object data, Paginated paginated,Object extraData) {
                    //提现成功
                    if (isnotNull()) {
                        if (mLifecycle.get() instanceof ActionPacketView.DepositView) {
                            ((ActionPacketView.DepositView) mLifecycle.get()).doDepositSuccess((String) data);
                        }
                    }
                }
            });
        }

    }

    //获取提现记录
    public void fetchHistoryDepositLog(int pageNO) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.PAGE, pageNO);
        map.put(AppConstants.FIELD.PAGESIZE, AppConstants.Const.PAGESIZE);
        invoke(mRestfull.fetchHistoryDepositLog(map), new Callback<List<UserDeposit>>());
    }

    public void fetchInviteUser(int pageNO) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.PAGE, pageNO);
        map.put(AppConstants.FIELD.PAGESIZE, AppConstants.Const.PAGESIZE);
        invoke(mRestfull.fetchUserShareList(map), new Callback<List<ShareUser>>());
    }

    //获取待审核提现
//	public void fetchWaitVertifyDeposit(int pageNO) {
//        invoke(mRestfull.fetchWaitVertifyDeposit(pageNO, AppConstants.Const.PAGESIZE), new Callback<List<UserDeposit>>());
//	}

//    //处理审核
//    public void HandleVertify(final UserDeposit item, int status, String content) {
//        invoke(mRestfull.HandleVertify(item.getOrderSn(),item.getType(),status,content),new Callback<Object>(){
//            @Override
//            public void onResponse(Object data, Paginated paginated) {
//                super.onResponse(data, paginated);
//                if(mLifecycle.get()!=null &&mLifecycle.get() instanceof ActionPacketView.VertifyView){
//                    ((ActionPacketView.VertifyView) mLifecycle.get()).doHandleSuccess(item);
//                }
//            }
//        });
//    }

    private int mTick = 0;

    protected Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != msg)
                switch (msg.what) {
                    case 0:
                        mTick--;
                        if (mTick >= 0 && isnotNull()) {
                            ((ActionPacketView.SmsAction) mLifecycle.get()).updateSmsCode(mTick);
                            handler.sendEmptyMessageDelayed(0, 1000);
                        }

                        break;
                    case 1://token刷新导致获取验证码失败，3s重试获取。
//						getSmsCode(user.getPhoneNo());
                        break;
                    default:
                        break;
                }
        }
    };

    /**
     * 获取验证码绑定支付宝
     */
    public void getSmsCodeForbindAliAccount() {
        if (null == user || StringUtils.isEmpty(user.getMobile()))
            return;
        invoke(mRestfull.getSmsCode(new GetSmsCodeParam(user.getMobile(), "1")), new Callback<UserSmsVo>());
    }

    /**
     * 绑定支付宝帐号
     *
     * @param strAliAccount
     * @param strUserName
     * @param s
     */
    public void bindAliAccount(String strAliAccount, String strUserName, String s) {
        Map<String, Object> params = new HashMap<>();
        params.put(AppConstants.FIELD.ALIACCOUNT, strAliAccount);
        params.put(AppConstants.FIELD.USER_REALNAME, strUserName);
        params.put(AppConstants.FIELD.SMSCODE, s);
        params.put(AppConstants.FIELD.SMS_TYPE, "1");
        params.put(AppConstants.FIELD.SNCODE, user.getSnCode());
        invoke(mRestfull.bindAliAccount(params), new Callback<BindAliUserAcount>() {
            @Override
            public void onResponse(BindAliUserAcount data, Paginated paginated,Object extraData) {
                super.onResponse(data, paginated,extraData);
                if (isnotNull() && mLifecycle.get() instanceof ActionPacketView.SmsAction) {
                    ((ActionPacketView.SmsAction) mLifecycle.get()).bindMobileSuccess(data);
                }
            }
        });
    }

    public void countSmsSend() {
        mTick = 60;
        handler.removeMessages(0);
        handler.sendEmptyMessage(0);
    }
}
